package com.hxgis.oc.controller;

import com.hxgis.auw.ApiWrapIgnore;
import com.hxgis.oc.util.ResponseHelper;
import com.hxgis.oc.util.w3d.OCServerDataManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/OCserver")
public class OCServerController {

    @ApiWrapIgnore
    @RequestMapping(value="/OC")
    public ResponseEntity<Object> getData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        byte[] res = null;
        HttpHeaders headers = null;

        String name = request.getParameter("name");
        String ext = request.getParameter("ext");
        String varName = request.getParameter("varName");
        String filter = request.getParameter("filter");

        File file = OCServerDataManager.getDataFilter(name,ext,varName,filter);

        if(file != null)
        {
            BufferedInputStream bf = new BufferedInputStream(Files.newInputStream(file.toPath()));
            res = new byte[bf.available()];
            bf.read(res);
            bf.close();
        }

        if(res!=null)
        {
            headers = ResponseHelper.createFileHeader(file.getName(),res.length);
        }

        return new ResponseEntity<>(res, headers, res == null ? HttpStatus.NOT_FOUND : HttpStatus.OK);
    }

}
